<template>
  <el-drawer v-model="open" title="房屋选择" size="80%">
    <el-row :gutter="20">
      <splitpanes :horizontal="appStore.device === 'mobile'" class="default-theme">
        <!--楼栋数据-->
        <pane size="16">
          <el-col>
            <div class="head-container">
              <el-input v-model="buildingName" placeholder="请输入楼栋名称" clearable prefix-icon="Search" style="margin-bottom: 20px" />
            </div>
            <div class="head-container">
              <el-tree :data="buildingOptions"  :expand-on-click-node="false" :filter-node-method="filterNode" ref="deptTreeRef" node-key="id" highlight-current default-expand-all @node-click="handleNodeClick" />
            </div>
          </el-col>
        </pane>
        <!--用户数据-->
        <pane size="76">
          <el-col>
            <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
               <el-form-item label="类别" prop="type">
                <el-select v-model="queryParams.type" placeholder="请选择类别" clearable style="width:120px">
                  <el-option
                    v-for="dict in building_type"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="名称" prop="name">
                <el-input
                  v-model="queryParams.name"
                  placeholder="请输入名称"
                  clearable
                  @keyup.enter="handleQuery"
                />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                <el-button icon="Refresh" @click="resetQuery">重置</el-button>
              </el-form-item>
            </el-form>

            <el-row :gutter="10" class="mb8">
              <el-col :span="1.5">
                <el-button v-if="props.mode == 'checkbox'"
                  type="primary"
                  plain
                  icon="Selection"
                  @click="handleSelect"
                >确定选择</el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button
                  type="danger"
                  plain
                  icon="Selection"
                  @click="handleClear"
                >清除选择</el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button
                  type="primary"
                  plain
                  icon="Selection"
                  @click="handleClose"
                >关闭</el-button>
              </el-col>
              <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
            </el-row>

            <el-table v-loading="loading" :data="roomList" @selection-change="handleSelectionChange">
              <el-table-column type="selection" width="55" align="center" />
              <el-table-column label="类别" align="center" prop="type">
                <template #default="scope">
                  <dict-tag :options="building_type" :value="scope.row.type"/>
                </template>
              </el-table-column>
              <el-table-column label="区域" align="center" prop="deptName" />
              <el-table-column label="楼栋" align="center" prop="buildingName" />
              <el-table-column label="单元号" align="center" prop="unitNum" />
              <el-table-column label="房屋名称" align="center" prop="name" />
              <el-table-column label="真实面积" align="center" prop="area" />
              <el-table-column label="户主" align="center" prop="personName" />
              <el-table-column label="状态" align="center" prop="status">
                <template #default="scope">
                  <dict-tag :options="room_status" :value="scope.row.status"/>
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template #default="scope">
                  <el-button link type="primary" icon="Selection" @click="handleSelect(scope.row)">选择</el-button>
                </template>
              </el-table-column>
            </el-table>
            <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
          </el-col>
        </pane>
      </splitpanes>
    </el-row>
  </el-drawer>
</template>

<script setup name="RoomSelection">
import { getToken } from "@/utils/auth";
import useAppStore from '@/store/modules/app'
import { listRoom, getRoom } from "@/api/archive/room";
import { dsData } from "@/api/dev/dataset";
import { Splitpanes, Pane } from "splitpanes"
import "splitpanes/dist/splitpanes.css"

const router = useRouter();
const appStore = useAppStore()
const { proxy } = getCurrentInstance();
const { building_type, room_status } = proxy.useDict('building_type', 'room_status');

const emit = defineEmits(['update:modelValue', 'select']);

const roomList = ref([]);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const names = ref([]);
const single = ref(true);
const multiple = ref(true);
const open = ref(false);
const total = ref(0);
const buildingName = ref("");
const buildingOptions = ref(undefined);
// 定义一个 ref 来存储默认展开的节点键值
const defaultExpandedKeys = ref([]);

const queryParams = ref({    
    pageNum: 1,
    pageSize: 10,
    orderByColumn: 't.id',
    isAsc: 'desc',
    deptId: null,
    buildingId: null,
    type: null,
    name: null,
    shapeId: null,
    personId: null,
    buyDate: null,
    status: null,
});

const props = defineProps({
  // 选中数据
  modelValue: [String, Number, Array],
  show: {
    type: Boolean,
    required:true,
    default: false
  },
  params: [String, Number, Array],
  limit: {
    type: Number,
    required: false,
    default: 1
  },
  // 分隔符号
  separator: {
    type: String,
    default: ',',
  }
});

watch(() => props.show, val => {
  open.value = val;
},{ deep: true, immediate: true });

watch(() => props.modelValue, val => {
  if(val){
    getRoom(val).then(response=>{
      ids.value = val;
      names.value = response.data.name;
    });
  }
},{ deep: true, immediate: true });


/** 查询用户列表 */
function getList() {
  loading.value = true;
  listRoom(queryParams.value).then(response => {
    roomList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
};


/** 通过条件过滤节点  */
const filterNode = (value, data) => {
  if (!value) return true;
  return data.label.indexOf(value) !== -1;
};

/** 根据名称筛选树 */
watch(buildingName, val => {
  proxy.$refs["deptTreeRef"].filter(val);
});

/** 节点单击事件 */
function handleNodeClick(data) {
  if(data.id.indexOf('_') > 0){
    queryParams.value.deptId = data.id.substring(2);
    queryParams.value.buildingId = null;
  }else{
    queryParams.value.deptId = null;
    queryParams.value.buildingId = data.id;
  }
  handleQuery();
};

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = [];
  proxy.resetForm("queryRef");
  queryParams.value.deptId = undefined;
  proxy.$refs.deptTreeRef.setCurrentKey(null);
  handleQuery();
};

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  names.value = selection.map(item => item.deptName + ' ' + item.buildingName + ' ' + item.unitNum + ' ' + item.name);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

function handleSelect(row) {
    if(row){
      ids.value = row.id;
      names.value = row.deptName + ' ' + row.buildingName + ' ' + row.unitNum + ' ' + row.name;
    }else if(ids.value.length == 0){
          proxy.$modal.msgError("请至少选择一条数据");
          return;
    }else if(props.limit > 0 && ids.value.length > props.limit){
          proxy.$modal.msgError("最多只能选择"+props.limit+"条数据");
          return;
    }
    emit("select", {id:ids.value, name: names.value, params: props.params});
    open.value = false;
}

function handleClear(){
  emit("select", null);
  open.value = false;
}
function handleClose(){
  open.value = false;
}

getList();

dsData('sys_building_tree').then(response => {
  buildingOptions.value = [];
  const data = { id: 0, label: '全部区域', children: [] };
  data.children = proxy.handleTree(response.data, "id", "pid");
  buildingOptions.value.push(data);
});
</script>